package com.donleo.oauth2.uaa.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.donleo.oauth2.common.model.User;
import com.donleo.oauth2.uaa.service.UserService;
import com.donleo.oauth2.uaa.dto.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author liangd
 * @since 2021-03-10 14:34
 */
@Service
public class SpringDataUserDetailsService implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //从数据库查询用户
        User user = userService.findUserByUsername(username);
        if (user == null) {
            //如果用户查不到，返回null，由provider来抛出异常
            return null;
        }
        //根据用户Id获取用户权限
        List<String> permissions = userService.findPermissionByUserId(user.getId());
        //集合转数组
        String[] permissionArray = new String[permissions.size()];
        permissions.toArray(permissionArray);
        UserDto userDto = UserDto.builder().id(user.getId().toString()).name(user.getName())
                .password(user.getPassword()).username(user.getUsername())
                .email(user.getEmail()).build();
        String principal = JSONObject.toJSONString(userDto);
        //将用户的部分信息存入userdetails中
        return org.springframework.security.core.userdetails.User.withUsername(principal).password(user.getPassword()).authorities(permissionArray).build();
    }
}
